package com.burt.http;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.burt.domain.Person;

/**
 * 把person转成properties格式
 * 
 * @author luowei1
 * @date 2018/7/4 15:20
 */
public class PersonHttpMessageConverter extends AbstractHttpMessageConverter<Person> {

    public PersonHttpMessageConverter() {
        super(MediaType.valueOf("application/properties+person"));
        setDefaultCharset(Charset.forName("UTF-8"));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(Person.class);
    }

    /**
     * 将请求内容中Properties内容转化成Person对象
     * 
     * @param clazz
     * @param httpInputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    protected Person readInternal(Class<? extends Person> clazz, HttpInputMessage httpInputMessage)
            throws IOException, HttpMessageNotReadableException {

        /**
         * person.id = 1 person.name = burt
         */
        InputStream inputStream = httpInputMessage.getBody();

        Properties properties = new Properties();
        //将请求的内容转化成Properties
        properties.load(new InputStreamReader(inputStream, getDefaultCharset()));

        Person person = new Person(Long.valueOf(properties.getProperty("person.id")),
                properties.getProperty("person.name"));

        return person;
    }

    /**
     * 把Person对象转化成Properties
     * 
     * @param person
     * @param httpOutputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage)
            throws IOException, HttpMessageNotWritableException {

        OutputStream outputStream = httpOutputMessage.getBody();

        Properties properties = new Properties();
        properties.setProperty("person.id", person.getId() + "");
        properties.setProperty("person.name", person.getName());
        properties.store(new OutputStreamWriter(outputStream, getDefaultCharset()), "Written by server");

    }
}
